<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: liangkun 2669681641@qq.com
 * @LastEditTime: 2023-11-21 16:06:07
 * @FilePath: \radiation-hygiene-fe\src\views\slide\detectionTogetherTask.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="单位名称" label-width="80px">
            <m-select
              v-model="queryParams.entrustOrganizationId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              filterable
              clearable
              :lists="entrustOrganizationSelect"
              lists_label="organizationName"
              lists_value="entrustOrganizationId"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="联系人">
            <el-input
              v-model="queryParams.contactsName"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="table-wrapper">
      <div class="tableoperation">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          v-hasPermi="['task:taskDetectionTogether:add']"
          @click.native.prevent="openDialog()"
          >添加</el-button
        >
        <el-button
          type="primary"
          size="mini"
          @click.native.prevent="handleOpenProjectTeamMembers"
          >项目组成员</el-button
        >
      </div>

      <el-table
        v-loading="loading"
        :data="detectionTogetherList"
        @row-dblclick="(row) => openDialog(row, '3')"
      >
        <el-table-column
          label="合同编号"
          align="center"
          prop="agreementNumber"
        />
        <el-table-column
          label="委托单位"
          align="center"
          prop="organizationName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="单位地址"
          align="center"
          prop="organizationAddress"
          :show-overflow-tooltip="true"
          width="150"
        />
        <el-table-column
          label="联系人"
          align="center"
          prop="contactsName"
          width="120"
        />
        <el-table-column
          label="联系电话"
          align="center"
          prop="contactsMobile"
          width="150"
        />
        <el-table-column
          label="任务要求完成日期"
          align="center"
          prop="personalDosimeterRequireCompletionDate"
        />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <dict-tag
              v-if="scope.row.assignState == 0"
              :options="dict.type.distribute_state"
              :value="scope.row.state"
            />
            <el-tag v-else :disable-transitions="true" type="info">
              二次派发
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="160"
        />
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-button
              v-if="row.state != '1'"
              v-hasPermi="['task:detectionTogether:edit']"
              @click.native.prevent="openDialog(row, '2')"
              type="text"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.state != '1'"
              v-hasPermi="['task:detectionTogether:assign']"
              @click.native.prevent="openDialog(row, '4')"
              type="text"
            >
              派发
            </el-button>
            <el-button type="text" style="color: #fff; width: 0">
              ' '
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 弹框 -->
    <el-dialog
      class="detection-together-dialog"
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1500px"
      v-dialogDrag="true"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formf"
        size="small"
        label-width="80px"
      >
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="单位名称" prop="entrustOrganizationId">
              <!-- <m-select
               :key="new Date().getDate()"
								v-model="form.entrustOrganizationId"
								:placeholder="status != '3' ? '输入文字检索查询' : ''"
								style="width: 100%"
								filterable
								:disabled="status != '1'"
								@change="changeEntrustOrganization"
								clearable
                :lists="entrustOrganizationSelect"
                lists_label="organizationName"
                lists_value="entrustOrganizationId"
                lists_key="entrustOrganizationId"
                :total="orgTotal"
                :pageSize="10"
                @handleChange="listeningEvent"
              >
							</m-select> -->
              <entrust-select
                :eid.sync="form.entrustOrganizationId"
                :deft="{
                  entrustOrganizationId: form.entrustOrganizationId,
                  organizationName: form.organizationName,
                }"
                @change="changeEntrustOrganization"
              >
              </entrust-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编号">
              <el-select
                v-model="form.agreementNumber"
                ref="agreement"
                @change="changeAgreement"
                :disabled="status != '1' && form.agreementNumber != null"
                :placeholder="status != '3' ? '请选择' : ''"
                style="width: 100%"
                clearable
              >
                <el-option
                  :label="item.agreementNumber"
                  :value="item.agreementNumber"
                  v-for="(item, index) in agreementList"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="5">
            <el-form-item label="派发人">
              <el-select
                v-model="form.taskAssignor"
                placeholder="请选择"
                style="width: 100%"
                clearable
                multiple
              >
                <el-option
                  :label="item.value"
                  :value="item.key"
                  v-for="(item, index) in assignorList"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input v-model="form.contactsName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input v-model="form.contactsMobile" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="单位地址" prop="provinceCode">
              <el-input v-model="form.organizationAddress" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        v-if="status != '1'"
        :data="form.tasksContractItemList"
        height="200"
      >
        <el-table-column
          label="设备类型"
          align="center"
          prop="entrustEquipmentTypeName"
          width="200"
        />
        <el-table-column label="检测类型" align="center">
          <template slot-scope="scope">
            <span
              class="cusinspectionTypeName"
              v-for="(item, index) in scope.row.cusinspectionTypeName"
              :key="index"
              >{{ item }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="单价"
          align="center"
          prop="amount"
          width="200"
        />
        <el-table-column label="总价" align="center" prop="total" width="200" />
      </el-table>

      <div class="innertitle" :class="status == '1' && 'add'">
        <span>检测清单</span>
        <el-button
          class="addline"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click.native.prevent="addline()"
          v-if="status != '3'"
          >添行</el-button
        >
      </div>
      <el-table
        :data="form.tasksContractEquipmentList"
        :height="status == '1' ? '400' : '230'"
      >
        <el-table-column label="序号" type="index" align="center" width="50" />
        <el-table-column label="设备名称" align="center" width="150">
          <template #default="scope">
            <el-select
              v-model="scope.row.entrustEquipmentId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              size="mini"
              :disabled="status == '3' || isTwoDistribute(scope.row)"
              filterable
              :ref="'equipment_' + scope.$index"
              @change="changeentrustEquipment($event, scope.$index)"
              clearable
            >
              <el-option
                :label="`${item.equipmentName}（${
                  item.equipmentNumber || '暂无设备编号'
                }）`"
                :value="item.equipmentId"
                v-for="(item, index) in entrustEquipmentSelect"
                :key="index"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="设备类型" align="center" width="150">
          <template #default="scope">
            <el-select
              v-model="scope.row.entrustEquipmentTypeCode"
              placeholder="请选择"
              style="width: 100%"
              size="mini"
              filterable
              clearable
            >
              <el-option
                :label="item.name"
                :value="item.equipmentTypeCode"
                v-for="(item, index) in entrustEquipmentTypeSelect"
                :key="index"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="规格及型号"
          align="center"
          prop="specificationModel"
          width="100"
        />
        <el-table-column
          label="生产厂家"
          align="center"
          prop="manufacturerName"
        />
        <el-table-column label="使用场所" align="center" prop="radiationSite" />
        <el-table-column label="购买时间" align="center" width="100">
          <template slot-scope="{ row }">
            {{ parseTime(row.purchaseTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="检测类别"
          align="center"
          prop="inspectionTypeId"
          width="150"
        >
          <template slot-scope="scope">
            <div class="inspect" v-if="scope.row.entrustEquipmentName">
              <!-- 个人剂量 -->
              <template v-if="scope.row.largeCategory == '2'">
                <el-checkbox-group
                  :disabled="status == '3' || isTwoDistribute(scope.row)"
                  class="inspectcheckbox"
                  v-model="scope.row.CG"
                >
                  <el-checkbox
                    v-for="(item, index) in CGInspectList"
                    :key="index"
                    :label="item.inspectionTypeId"
                    >{{ item.typeName }}</el-checkbox
                  >
                </el-checkbox-group>
              </template>
              <!-- 工业检测 -->
              <template v-else-if="scope.row.largeCategory == '3'">
                <el-checkbox
                  v-model="scope.row.radioInspecId"
                  disabled
                  checked
                  :true-label="FHInspectList[0].inspectionTypeId"
                  :label="FHInspectList[0].inspectionTypeId"
                  >防护检测</el-checkbox
                >
              </template>
              <!-- 其他 -->
              <template v-else>
                <div style="text-align: left">
                  <el-checkbox-group
                    :disabled="status == '3' || isTwoDistribute(scope.row)"
                    class="inspectcheckbox"
                    v-model="scope.row.FH"
                  >
                    <el-checkbox
                      v-for="(item, index) in FHInspectList"
                      :key="index"
                      :label="item.inspectionTypeId"
                      >{{ item.typeName }}</el-checkbox
                    >
                  </el-checkbox-group>
                  <el-radio-group
                    :disabled="status == '3' || isTwoDistribute(scope.row)"
                    class="inspectradio"
                    v-model="scope.row.radioInspecId"
                  >
                    <el-radio
                      v-for="(item, index) in radioInspectList"
                      :key="index"
                      :label="item.inspectionTypeId"
                      @click.native.prevent="
                        handleChangeRadioInspecId(
                          scope.row,
                          scope.$index,
                          item.inspectionTypeId
                        )
                      "
                      >{{ item.typeName }}</el-radio
                    >
                  </el-radio-group>
                  <br />
                  <el-checkbox v-model="scope.row.checkboxInspecId2" label="9"
                    >环境检测</el-checkbox
                  >
                </div>
              </template>
            </div>
            <div v-if="scope.row.radioInspecId == 4">
              稳定性周期:
              <el-select
                style="width: 100px"
                v-model="scope.row.stabilityCycle"
              >
                <el-option
                  v-for="item in dict.type.stability_cycle"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"
                ></el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="退回原因" align="center" prop="backReason">
          <template slot-scope="{ row }">
            <span style="color: red">{{ row.backReason }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="检测项目"
          align="center"
          prop="inspectionCategory"
          width="150"
        />
        <el-table-column
          v-if="status != '3'"
          align="center"
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteData(scope.$index)"
              type="text"
              style="color: #f32d2d"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="status == '2' || status == '3' || status == '4'">
        <div class="innertitle task">
          <span>任务信息</span>
        </div>
        <el-form
          :model="form"
          :disabled="status == '3'"
          :rules="rulesAssign"
          ref="formAssign"
          size="small"
          label-width="120px"
        >
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="要求完成日期">
                <el-date-picker
                  style="width: 100%"
                  v-model="form.personalDosimeterRequireCompletionDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  :placeholder="status != '3' ? '请选择' : ''"
                  :picker-options="{
                    disabledDate: (time) =>
                      time.getTime() <
                      new Date(new Date().setHours(0, 0, 0, 0)),
                  }"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="任务指派人"
                label-width="100px"
                :prop="assignDisabled ? 'taskAssignor' : 'taskAssignor'"
              >
                <el-select
                  v-model="form.taskAssignor"
                  :placeholder="status != '3' ? '请选择' : ''"
                  style="width: 100%"
                  filterable
                  :disabled="assignDisabled && false"
                  multiple
                  clearable
                >
                  <el-option
                    :label="item.value"
                    :value="item.key"
                    v-for="(item, index) in assignorList"
                    :key="index"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button type="primary" size="small" @click="handleOpenTaskPlan"
                >任务计划</el-button
              >
              <el-button
                type="primary"
                size="small"
                :loading="generateBtnLoading"
                :disabled="false"
                @click="handleGenerateTaskPlan"
                >生成项目策划书</el-button
              >
              <el-button
                type="primary"
                size="small"
                :disabled="false"
                @click="handlePrintTaskPlan"
                v-if="planOssId"
                >项目策划书</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer">
        <el-button
          type="primary"
          v-if="status == '1' || status == '2'"
          @click="submitForm"
          :loading="app_loading.show"
          >确 定</el-button
        >
        <el-button type="success" v-if="status == '4'" @click="submitForm(true)"
          >派 发</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <ProjectTeamMembersDialog
      :show.sync="showProjectTeamMembersDialog"
    ></ProjectTeamMembersDialog>

    <DetectionTaskPlanDialog
      :show.sync="showDetectionTaskPlanDialog"
      :row="currRow"
    ></DetectionTaskPlanDialog>
  </div>
</template>

<script>
import {
  detectionTogetherEdit,
  detectionTogetherAssign,
  queryDetectionProjectList,
  detectionTogetherAdd,
  detectionTogetherList,
  detectionTogetherDetail,
  getAssignorList,
  generateDetectionTaskPlanDocument,
} from "@/api/slides/detectionTogether";
import {
  entrustOrganizationListing,
  entrustOrganizationDetail,
  entrustOrganizationList,
} from "@/api/person/entrustOrganization";
import { getAgreementListWithTaskTogether } from "@/api/person/entrustAgreement";
import { entrustEquipmentTypeListing } from "@/api/person/entrustEquipmentType";
import { entrustEquipmentListing } from "@/api/person/entrustEquipment";
import { getInspectionList } from "@/api/slides/contractTask";
import { listByIds } from "@/api/system/oss";
import MSelect from "@/components/mSelect";
import entrustSelect from "@/components/select/src/entrustSelect";
import ProjectTeamMembersDialog from "./component/ProjectTeamMembersDialog.vue";
import DetectionTaskPlanDialog from "./component/DetectionTaskPlanDialog.vue";

export default {
  name: "detectionTogetherTask",
  components: {
    MSelect,
    entrustSelect,
    ProjectTeamMembersDialog,
    DetectionTaskPlanDialog,
  },
  dicts: ["distribute_state", "stability_cycle"],
  inject: ["getAppLoading"],
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      // 视图高度
      height: document.documentElement.clientHeight,
      // 表单参数
      form: {},
      loading: false,
      status: null,
      title: null,
      rules: {
        entrustOrganizationId: [
          { required: true, message: "单位名称不能为空", trigger: "change" },
        ],
      },
      rulesAssign: {
        taskAssignor: [
          { required: true, message: "任务指派人不能为空", trigger: "change" },
        ],
      },
      // 委托单位下拉框
      entrustOrganizationSelect: [],
      // 设备类型下拉框
      entrustEquipmentTypeSelect: [],
      // 检测类型下拉框
      inspectionList: [],
      CGInspectList: [],
      FHInspectList: [],
      radioInspectList: [],
      // 委托单位设备下拉框
      entrustEquipmentSelect: [],
      entrustEquipmentTypeList: [],
      // 检测总任务列表
      detectionTogetherList: [],
      // 合同下拉框
      agreementList: [],
      // 任务指派人下拉框
      assignorList: [],
      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
      currRow: {},
      showProjectTeamMembersDialog: false,
      showDetectionTaskPlanDialog: false,
      generateBtnLoading: false,
      planOssId: null,
    };
  },
  created() {
    this.getList();
    // 未发起栏的权限控制（领导层没有）
    // let permissions = this.$store.getters.permissions;
    // let found = permissions.find((item) => {
    //   return item == "task:tasksContract:apply";
    // });
    // this.isPer = found == "task:tasksContract:apply" || permissions == "*:*:*";
    // if (this.isPer) {
    //   this.getInspectionListing();
    // }
    this.getInspectionListing();
    this.getEntrustEquipmentTypeListing();
    this.handleGetAssignorList();
  },
  computed: {
    app_loading() {
      return this.getAppLoading();
    },
    // 如果检测设备只有剂量计 则禁用指派人
    assignDisabled() {
      let index = this.form.tasksContractEquipmentList?.findIndex(
        (item) =>
          item.entrustEquipmentName &&
          item.entrustEquipmentName.indexOf("个人剂量") == -1
      );
      // console.log("index", index, this.form.tasksContractEquipmentList);
      // return this.form.tasksContractEquipmentList?.length != 0 && index == -1;
      return index == -1;
    },
  },
  methods: {
    // 获取检测总任务列表
    getList() {
      this.loading = true;
      detectionTogetherList(this.queryParams)
        .then((response) => {
          this.detectionTogetherList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.entrustOrganizationSelect.push(...response.rows);
        } else {
          this.entrustOrganizationSelect = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 获取设备类型下拉框
    getEntrustEquipmentTypeListing() {
      entrustEquipmentTypeListing().then((response) => {
        this.entrustEquipmentTypeSelect = response.data;
      });
    },
    // 获取检测类型下拉框
    getInspectionListing() {
      getInspectionList().then((response) => {
        this.inspectionList = response.rows;
        this.CGInspectList = this.inspectionList.filter((item) => {
          return item.typeName == "常规监测";
        });
        this.FHInspectList = this.inspectionList.filter((item) => {
          return item.typeName == "防护检测";
        });
        this.radioInspectList = this.inspectionList.filter((item) => {
          return item.typeName != "常规监测" && item.typeName != "防护检测";
        });
        console.log("this.CGInspectList", this.CGInspectList);
        console.log("this.FHInspectList", this.FHInspectList);
        console.log("this.radioInspectList", this.radioInspectList);
      });
    },
    // 获取派发人下拉框
    handleGetAssignorList() {
      getAssignorList().then((response) => {
        this.assignorList = response.data || [];
      });
    },
    // 打开对话框
    async openDialog(row, status) {
      this.currRow = row;
      this.form = {};
      this.agreementList = [];
      this.resetForm("formf");
      this.resetForm("formAssign");
      if (row) {
        detectionTogetherDetail(row.taskDetectionTogetherId).then(
          (response) => {
            let responsedata = response.data;
            this.planOssId = responsedata.planOssId;
            if (
              responsedata.tasksContractItemList &&
              responsedata.tasksContractItemList.length != 0
            ) {
              responsedata.tasksContractItemList.forEach((item) => {
                item.amount /= 100;
                item.total = item.num * item.amount;
                item.CG = [];
                item.FH = [];
                item.checkboxInspecId2 = "";
                item.radioInspecId = null;
                let arr = item.inspectionTypeId.split(",");
                item.cusinspectionTypeName = [];
                arr.forEach((id) => {
                  let obj = this.inspectionList.find((it) => {
                    return it.inspectionTypeId == id;
                  });
                  if (obj) {
                    item.cusinspectionTypeName.push(obj.typeName);
                  }
                });
              });
            }
            if (
              responsedata.tasksContractEquipmentList &&
              responsedata.tasksContractEquipmentList.length != 0
            ) {
              responsedata.tasksContractEquipmentList.forEach((item, index) => {
                item.CG = [];
                item.FH = [];
                item.checkboxInspecId2 = "";
                item.radioInspecId = null;
                let arr = item.inspectionTypeId.split(",");
                arr.forEach((itemid) => {
                  let findObj = this.inspectionList.find((inspectionitem) => {
                    return inspectionitem.inspectionTypeId == itemid;
                  });
                  if (findObj) {
                    if (findObj.typeName == "常规监测") {
                      this.$set(item, "CG", [findObj.inspectionTypeId]);
                    } else if (findObj.typeName == "防护检测") {
                      this.$set(item, "FH", [findObj.inspectionTypeId]);
                    } else {
                      this.$set(
                        item,
                        "radioInspecId",
                        findObj.inspectionTypeId
                      );
                    }
                  }
                });
              });
              // 带出委托单位信息
              let obj = this.entrustOrganizationSelect.find((item) => {
                return item.organizationName == responsedata.organizationName;
              });
              if (
                obj &&
                responsedata.entrustOrganizationId == obj.entrustOrganizationId
              ) {
                responsedata.entrustOrganizationId = obj.entrustOrganizationId;
                responsedata.contactsName = obj.contactsName;
                responsedata.organizationAddress = obj.addressDetails;
                responsedata.contactsMobile = obj.contactsMobile;
              }
            }
            this.form = responsedata;
            if (this.form.entrustOrganizationId) {
              getAgreementListWithTaskTogether({
                entrustOrganizationId: this.form.entrustOrganizationId,
              }).then((response) => {
                this.agreementList = response.data;
              });
              entrustEquipmentListing({
                entrustOrganizationId: this.form.entrustOrganizationId,
              }).then((response) => {
                this.entrustEquipmentSelect = response.data;
                this.form.tasksContractEquipmentList?.forEach((item, index) => {
                  this.changeentrustEquipment(
                    item.entrustEquipmentId,
                    index,
                    true
                  );
                });
              });
            }
            if (
              response.data?.taskAssignor &&
              response.data?.assignState == 0
            ) {
              this.$set(
                this.form,
                "taskAssignor",
                response.data.taskAssignor.split(",")
              );
            } else {
              this.$set(this.form, "taskAssignor", []);
            }
            console.log("this.form.taskAssignor", this.form.taskAssignor);
          }
        );
        if (status == "3") {
          this.status = "3";
          this.title = "查看检测任务";
        }
        if (status == "2") {
          this.status = "2";
          this.title = "编辑检测任务";
        }
        if (status == "4") {
          this.status = "4";
          this.title = "派发检测任务";
        }
        this.dialogVisible = true;
      } else {
        this.form = {
          contactsName: null,
          organizationAddress: null,
          contactsMobile: null,
          tasksContractItemList: [],
          tasksContractEquipmentList: [],
        };
        this.status = "1";
        this.title = "添加检测任务";
        this.dialogVisible = true;
      }
    },
    // 打开项目组成员
    handleOpenProjectTeamMembers() {
      this.showProjectTeamMembersDialog = true;
    },
    // 判断为二次派发状态
    isTwoDistribute(row) {
      return this.form.assignState == 1 && row.isBack == 0;
    },
    // 提交按钮
    submitForm(status) {
      this.$refs["formf"].validate((valid) => {
        if (!valid) return;
        let copyForm = JSON.parse(JSON.stringify(this.form));
        // if (copyForm.tasksContractEquipmentList.length == 0) {
        //   this.$modal.msgWarning("请添加检测清单");
        //   return;
        // }
        let isEmpty = copyForm.tasksContractEquipmentList.some((item) => {
          if (!item.entrustEquipmentId) {
            this.$modal.msgWarning("设备名称不能为空");
            return true;
          }
          if (
            item.CG.length == 0 &&
            item.FH.length == 0 &&
            !item.radioInspecId &&
            !item.checkboxInspecId2
          ) {
            this.$modal.msgWarning("检测类型不能为空");
            return true;
          }
        });
        if (isEmpty) {
          /* 有空值 */
          return;
        } else {
          /* 都有值 */
          copyForm.tasksContractEquipmentList.forEach((item) => {
            let arr = [];
            if (item.CG.length != 0) {
              arr.push(...item.CG);
            }
            if (item.FH.length != 0) {
              arr.push(...item.FH);
            }
            if (item.radioInspecId) {
              arr.push(item.radioInspecId);
            }
            arr = Array.from(new Set(arr));
            item.inspectionTypeId = arr.join(",");
            if (item.checkboxInspecId2) {
              item.inspectionTypeId += ",9";
            }
            delete item.CG;
            delete item.FH;
            delete item.checkboxInspecId2;
            delete item.radioInspecId;
          });
        }
        copyForm.taskAssignor = copyForm.taskAssignor?.join(",");
        if (this.status == "1") {
          detectionTogetherAdd(copyForm).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.dialogVisible = false;
            this.getList();
          });
        } else if (this.status == "2") {
          detectionTogetherEdit(copyForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.getList();
          });
        } else if (status) {
          this.$refs["formAssign"].validate((valid) => {
            if (!valid) return;
            // this.assignDisabled && (copyForm.taskAssignor = "");
            // copyForm.taskAssignor = this.assignDisabled ? "" : copyForm.taskAssignor.join(',');
            detectionTogetherAssign(copyForm).then((response) => {
              this.$modal.msgSuccess("派发成功");
              this.dialogVisible = false;
              this.getList();
            });
          });
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm(`是否确认删除剂量元件码[${row.slidesNumber}]？`)
        .then(() => {
          this.loading = true;
          return slidesDelete(row.registrationSlidesId);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 删除弹框里列表
    deleteData(index) {
      this.$modal.confirm(`是否确认删除该数据？`).then(() => {
        this.form.tasksContractEquipmentList.splice(index, 1);
      });
    },
    // 导出
    handleExport() {
      this.download(
        "/basic/entrust/radiationSite/export",
        {
          ...this.queryParams,
        },
        `放射场所.xlsx`
      );
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 更改委托单位下拉
    changeEntrustOrganization(val) {
      // 重新获取设备下拉框并清空设备列表
      entrustEquipmentListing({
        entrustOrganizationId: this.form.entrustOrganizationId,
      }).then((response) => {
        this.entrustEquipmentSelect = response.data || [];
      });
      this.$set(this.form, "tasksContractEquipmentList", []);

      let obj = this.entrustOrganizationSelect.find((item) => {
        return item.entrustOrganizationId == val.entrustOrganizationId;
      });
      if (!obj) {
        this.form.contactsName = null;
        this.form.organizationAddress = null;
        this.form.contactsMobile = null;
        this.form.agreementNumber = null;
        this.agreementList = [];
        return;
      }
      this.form.contactsName = obj.contactsName;
      this.form.organizationAddress = obj.addressDetails;
      this.form.contactsMobile = obj.contactsMobile;
      this.$set(this.form, "agreementId", null);
      this.$set(this.form, "agreementNumber", null);
      getAgreementListWithTaskTogether({
        entrustOrganizationId: val.entrustOrganizationId,
      }).then((response) => {
        this.agreementList = response.data;
      });
    },
    // 更改合同下拉
    changeAgreement(val) {
      let obj = this.agreementList.find((item) => {
        return item.agreementNumber == val;
      });
      if (obj) {
        this.$set(this.form, "agreementId", obj.agreementId);
      }
    },
    // 更改设备下拉
    changeentrustEquipment(val, index, isReset) {
      let obj = this.entrustEquipmentSelect.find((item) => {
        return item.equipmentId == val;
      });
      this.$set(
        this.form.tasksContractEquipmentList[index],
        "entrustEquipmentTypeCode",
        obj?.entrustEquipmentTypeCode || null
      );
      this.$set(
        this.form.tasksContractEquipmentList[index],
        "specificationModel",
        obj?.specificationModel || null
      );
      this.$set(
        this.form.tasksContractEquipmentList[index],
        "manufacturerName",
        obj?.manufacturerName || null
      );
      this.$set(
        this.form.tasksContractEquipmentList[index],
        "radiationSite",
        obj?.radiationSite || null
      );
      this.$set(
        this.form.tasksContractEquipmentList[index],
        "purchaseTime",
        obj?.purchaseTime || null
      );
      this.$set(
        this.form.tasksContractEquipmentList[index],
        "largeCategory",
        obj?.largeCategory || null
      );
      if (obj && obj.equipmentName.indexOf("个人剂量") != -1) {
        this.$set(
          this.form.tasksContractEquipmentList[index],
          "inspectionCategory",
          "X/γ射线外照射个人剂量检测"
        );
      } else {
        this.$set(
          this.form.tasksContractEquipmentList[index],
          "inspectionCategory",
          null
        );
      }
      this.$nextTick(() => {
        this.$set(
          this.form.tasksContractEquipmentList[index],
          "entrustEquipmentName",
          this.$refs[`equipment_${index}`].selectedLabel
        );
      });
      // 重置值
      if (!isReset) {
        this.form.tasksContractEquipmentList[index].CG = [];
        this.form.tasksContractEquipmentList[index].FH = [];
        this.form.tasksContractEquipmentList[index].checkboxInspecId2 = "";
        this.form.tasksContractEquipmentList[index].radioInspecId = null;
      }
    },
    // 添行
    addline() {
      this.$refs["formf"].validate((valid) => {
        if (!valid) return;
        let index = this.form.tasksContractEquipmentList?.length || 0;
        this.$set(this.form.tasksContractEquipmentList, index, {
          CG: [],
          FH: [],
          checkboxInspecId2: "",
          radioInspecId: null,
          total: null,
        });
      });
    },
    // 单选框可取消
    handleChangeRadioInspecId(row, index, changeId) {
      let newRow = {
        ...row,
        radioInspecId: row.radioInspecId === changeId ? "" : changeId,
      };
      this.$set(this.form.tasksContractEquipmentList, index, newRow);
    },
    // 打开任务计划
    handleOpenTaskPlan() {
      this.showDetectionTaskPlanDialog = true;
    },
    // 生成项目策划书
    handleGenerateTaskPlan() {
      this.generateBtnLoading = true;
      const taskDetectionTogetherId = this.currRow.taskDetectionTogetherId;
      generateDetectionTaskPlanDocument(taskDetectionTogetherId)
        .then((res) => {
          this.generateBtnLoading = false;
          this.$message.success("生成成功");
          this.planOssId = res.data || "";
        })
        .catch((err) => {
          this.generateBtnLoading = false;
        });
    },
    // 打印项目策划书
    handlePrintTaskPlan() {
      listByIds(this.planOssId)
        .then((res) => {
          const fileUrl = res.data[0].url;
          window.open(fileUrl, "PDF", "");
        })
        .catch((err) => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}

.operation {
  margin-bottom: 15px;
  .register {
    padding-inline: 30px;
  }
}
.uploadbutton {
  padding-inline: 20px;
}
.myupload {
  margin-bottom: 20px;
}
.result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  .calc {
    width: min-content;
    margin-left: 20px;
    .el-button {
      margin: 0;
      &:nth-of-type(1) {
        margin-bottom: 10px;
      }
    }
  }
}
.nametitle {
  text-align: center;
  margin-bottom: 10px;
  font-weight: bolder;
  &::before {
    content: "* ";
    color: red;
  }
}
.el-table .warning-row {
  background: rgb(228, 13, 13);
}
.searchcontainer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  margin-top: -10px;
}
.viewform {
  justify-content: flex-end;
}
.title {
  padding-left: 10px;
  border-left: 5px solid #2a72ee;
  text-align: left;
  font-weight: bolder;
  font-size: 16px;
  margin-bottom: 30px;
}

.innertitle {
  margin-bottom: 10px;
  position: relative;
  color: #252d57;
  font-weight: bold;
  padding-left: 15px;
  font-size: 18px;
  line-height: 20px;
  margin-top: 20px;
  &.add {
    margin-top: 0;
  }
  &::before {
    content: "";
    width: 5px;
    height: 100%;
    background-color: #2a72ee;
    border-radius: 5px;
    position: absolute;
    left: 0;
    bottom: 0;
  }
  .addline {
    float: right;
    padding-inline: 20px;
    transform: translateY(-7px);
  }
}
.inspect {
  display: flex;
  align-items: center;
  justify-content: center;
  .inspectcheckbox {
    margin-right: 20px;
    display: flex;
    align-items: center;
  }
  .inspectradio {
    .el-radio {
      margin-right: 13px;
    }
  }
}
.cusinspectionTypeName {
  margin-right: 20px;
  &:nth-last-child(1) {
    margin-right: 0;
  }
}

.detection-together-dialog {
  ::v-deep .el-dialog {
    overflow: unset !important;
  }
  ::v-deep .el-dialog__body {
    max-height: 80vh;
    overflow-y: auto;
  }
}
</style>
